﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.Tools.Helper
{
    /// <summary>
    /// JSON文件读写帮助类
    /// </summary>
    public static class JsonHelper
    {
        /// <summary>
        /// 读JSON
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <returns></returns>
        public static T Load<T>(string path)
        {
            if(!File.Exists(path))
            {
                return default(T);
            }

            string content = File.ReadAllText(path);
            return Deserialize<T>(content);
        }

        public static T Deserialize<T>(string content)
        {
            return JsonConvert.DeserializeObject<T>(content);
        }

        /// <summary>
        /// 写JSON
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="fullName"></param>
        /// <param name="indented"></param>
        public static void Write(object obj,string fullName,bool indented = false)
        {
            string content = Serialize(obj, indented);
            File.WriteAllText(fullName, content);
        }

        public static string Serialize(object obj, bool indented = false)
        {
            Formatting formatting = indented ? Formatting.Indented : Formatting.None;
            return JsonConvert.SerializeObject(obj, formatting);
        }
    }    
}
